//
//  MSRequestObject.m
//  Musou
//
//  Created by danal on 13-3-18.
//
//

#import "MSRequestObject.h"

@interface MSRequestObject ()
@property (strong, nonatomic) MSHTTPRequest *request;
@end

@implementation MSRequestObject
@synthesize request = _request;
@synthesize url = _url;
@synthesize post = _post;
@synthesize requestParams = _requestParams;
@synthesize delegate = _delegate;
@synthesize completeBlock = _completeBlock;
@synthesize requestSender = _requestSender;

- (void)dealloc{
#ifdef DEBUG
    NSLog(@"-[%@ dealloc]", NSStringFromClass([self class]));
#endif
    [_request cancel];
    self.request = nil;
    
    self.delegate = nil;
    
    [_url release];
    
    Block_release(_completeBlock);
    _completeBlock = NULL;
    _requestSender = nil;
    
    [_requestParams release];
    _requestParams = nil;
    
    [super dealloc];
}

- (id)init{
    self = [super init];
    if (self) {
        _request = [[MSHTTPRequest alloc] initWithDelegate:self];
        _requestParams = [[NSMutableDictionary alloc] init];
        _request.parseJson = YES;
    }
    return self;
}

- (id)initWithUrl:(NSString *)url{
    self = [self init];
    if (self) {
        self.url = url;
    }
    return self;
}

//Prepare request parameters,Override it if you want to fill parameters by custom
- (void)prepare{
    for (NSString *key in self.requestParams){
        id val = [self.requestParams objectForKey:key];
        if ([val isKindOfClass:[NSString class]]
            || [val isKindOfClass:[NSNumber class]]){
            [self.request addValue:val forField:key];
        } 
    }
}

- (void)setValue:(id)value forField:(NSString *)field{
    if (value == nil || [value isKindOfClass:[NSError class]]) {
        value = @"";
    }
    [self.requestParams setObject:value forKey:field];
}

- (void)setGetValue:(id)value forField:(NSString *)field{
    NSString *param = [NSString stringWithFormat:@"%@=%@",field,value];
    if ([self.url rangeOfString:param].length > 0) {
        //param exists, ignore it
        return;
    }
    
    NSMutableString *url = [NSMutableString stringWithString:self.url];
    if ([url rangeOfString:@"?"].length == 0) {
        [url appendString:@"?"];
    }
    [url appendFormat:@"&%@",param];
    self.url = url;
}

- (void)setUrl:(NSString *)url{
    if (_url != url) {
        [_url release];
        _url = [url copy];
        _request.URL = [NSURL URLWithString:_url];
    }
}

- (void)startRequest:(BOOL)post{
    _post = post;
    [self start];
}

- (void)startGetWithDelegate:(id<MSRequestObjectDelegate>)delegate{
    self.delegate = delegate;
    [self startRequest:NO];
}

- (void)startPostWithDelegate:(id<MSRequestObjectDelegate>)delegate{
    self.delegate = delegate;
    [self startRequest:YES];
}

- (void)startGetWithBlock:(void (^)(id, NSError *, id))block sender:(id)object{
    _requestSender = object;
    self.completeBlock = block;
    [self startRequest:NO];
}

- (void)startPostWithBlock:(void (^)(id, NSError *, id))block sender:(id)object{
    _requestSender = object;
    self.completeBlock = block;
    [self startRequest:YES];
}

- (void)start{
    [self prepare];
    _request.postMethod = _post;
    [_request start];

}

- (void)cancel{
    self.delegate = nil;
    self.request.delegate = nil;
    [self.request cancel];
}

- (void)parse:(id)result{
    NSLog(@"Override this method %s to parse the result data", __func__);
}

#pragma mark - MSHTTPRequestDelegate

- (void)requestDidStartLoading:(MSHTTPRequest *)req{
    if (self.delegate && [self.delegate respondsToSelector:@selector(onRequestStart:)]) {
        [self.delegate onRequestStart:self];
    }
}

- (void)requestDidFinishLoading:(MSHTTPRequest *)req error:(NSError *)error{
    id json = req.result;
    if ([json isKindOfClass:[NSDictionary class]] || [json isKindOfClass:[NSArray class]]) {
        [self parse:json];
    }
    
    //Using delegate
    if (self.delegate && [self.delegate respondsToSelector:@selector(onRequestComplete:error:)]) {
        [self.delegate onRequestComplete:self error:error];
    }
    
    //Using block
    if (_completeBlock != NULL) {
        _completeBlock(self, error, _requestSender);
    }
}


@end

